package leetcode;


public class l0021_合并两个有序链表_解法_无头结点 {

    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if (list1 == null) {
            return list2;
        }
        if (list2 == null) {
            return list1;
        }
        ListNode cur1 = list1;
        ListNode cur2 = list2;

        ListNode newHead = null;
        if (cur1.val < cur2.val) {
            newHead = cur1;
            cur1 = cur1.next;
        } else {
            newHead = cur2;
            cur2 = cur2.next;
        }
        ListNode result=newHead;
        while (cur1 != null && cur2 != null) {
            if (cur1.val < cur2.val) {
                newHead.next = cur1;
                cur1 = cur1.next;
                newHead = newHead.next;
            } else {
                newHead.next = cur2;
                cur2 = cur2.next;
                newHead = newHead.next;
            }
        }
        if (cur1 != null) {
            newHead.next = cur1;
        }
        if (cur2 != null) {
            newHead.next = cur2;
        }
        return result;
    }
}
